from django.contrib import admin
from .models import SKU
from django.core.cache import caches


GOODS_INDEX_CACHE = caches["goods_index"]
GOODS_DETAIL_CACHE = caches["goods_detail"]


@admin.register(SKU)
class SKUAdmin(admin.ModelAdmin):
    # 重写ModelAdmin中的save_model()方法
    def save_model(self, request, obj, form, change):
        # 执行父类方法:更新mysql数据
        super().save_model(request, obj, form, change)
        # 清除首页缓存
        GOODS_INDEX_CACHE.clear()
        print("更新数据时,首页缓存清除~~~")
        # 清除详情页缓存
        key = "gd%s" % obj.id
        GOODS_DETAIL_CACHE.delete(key)
        print("更新数据时,详情页缓存清除~~~")

    # 重写ModelAdmin中的delete_model()方法
    def delete_model(self, request, obj):
        super().delete_model(request, obj)
        GOODS_INDEX_CACHE.clear()
        # 清除详情页缓存
        key = "gd%s" % obj.id
        GOODS_DETAIL_CACHE.delete(key)
        print("删除数据时,详情页缓存清除~~~")












